<template>
  <div>
    <div style="margin: 24px;">
      <a-card title="营收数据" :bordered="false">
        <template slot="extra">
          <date-searcher @change="initDateSearch" />&nbsp;
          <router-link to="/dataBI/reportDetail">
            查看报表
            <a-icon type="right-circle" theme="twoTone" />
          </router-link>
        </template>
        <a-row :gutter="20">
          <a-col :span="16">
            <h1 class="headTitle">营收统计</h1>
            <a-row style="padding: 15px 2px;margin-bottom: 20px;">
              <a-col :span="6">
                <p>总应收(元)</p>
                <h2>{{detail.jtReceivableAmount}}</h2>
                <p>
                  {{detail.jtReceivableAmountChangeRate}} %
                  <a-icon
                    v-if="detail.jtReceivableAmountChangeRate && detail.jtReceivableAmountChangeRate > 0"
                    type="arrow-up"
                    style="color: green"
                  />
                  <a-icon
                    v-if="detail.jtReceivableAmountChangeRate && detail.jtReceivableAmountChangeRate < 0"
                    type="arrow-down"
                    style="color: red"
                  />
                </p>
              </a-col>
              <a-col :span="6">
                <p>总应付(元)</p>
                <h2>{{detail.jtPayableAmount}}</h2>
                <p>
                  {{detail.jtPayableAmountChangeRate}} %
                  <a-icon
                    v-if="detail.jtPayableAmountChangeRate && detail.jtPayableAmountChangeRate > 0"
                    type="arrow-up"
                    style="color: green"
                  />
                  <a-icon
                    v-if="detail.jtPayableAmountChangeRate && detail.jtPayableAmountChangeRate < 0"
                    type="arrow-down"
                    style="color: red"
                  />
                </p>
              </a-col>
              <a-col :span="6">
                <p>总毛利(元)</p>
                <h2>{{detail.jtProfit}}</h2>
                <p>
                  {{detail.jtProfitChangeRate}} %
                  <a-icon
                    v-if="detail.jtProfitChangeRate && detail.jtProfitChangeRate > 0"
                    type="arrow-up"
                    style="color: green"
                  />
                  <a-icon
                    v-if="detail.jtProfitChangeRate && detail.jtProfitChangeRate < 0"
                    type="arrow-down"
                    style="color: red"
                  />
                </p>
              </a-col>
              <a-col :span="6">
                <p>毛利率</p>
                <h2>{{detail.jtProfitRate}} %</h2>
                <p>
                  {{detail.jtProfitRateChangeRate}} %
                  <a-icon
                    v-if="detail.jtProfitRateChangeRate && detail.jtProfitRateChangeRate > 0"
                    type="arrow-up"
                    style="color: green"
                  />
                  <a-icon
                    v-if="detail.jtProfitRateChangeRate && detail.jtProfitRateChangeRate < 0"
                    type="arrow-down"
                    style="color: red"
                  />
                </p>
              </a-col>
            </a-row>

            <h1 class="headTitle">营收曲线</h1>
            <div id="bar1" style="height: 450px;"></div>
          </a-col>
          <a-col :span="8">
            <h1 class="headTitle">
              订单占比&nbsp;
              <a-radio-group v-model="orderTypeCurrent" @change="onChangeType">
                <a-radio-button v-for="v in radioGroup" :key="v.key" :value="v.key">{{v.title}}</a-radio-button>
              </a-radio-group>
              <div style="text-align: center;">
                <div id="bar2" style="height: 350px;"></div>

                <div style="display: inline-block; text-align: left;">
                  <p v-for="(v, i) in orderRates" :key="i">
                    <a-badge :color="v.itemStyle.color" :text="v.nameEl" style="width: 110px"></a-badge>
                    <small
                      style="display: inline-block; color: grey; width: 100px; margin-right: 20px;"
                    >| {{v.rate}}%</small>
                    <span>{{v.num}}</span>
                  </p>
                </div>
              </div>
            </h1>
          </a-col>
        </a-row>
      </a-card>
    </div>
    <div style="margin: 24px;">
      <a-card title="年度运营指标" :bordered="false">
        <template slot="extra">
          <a-date-picker
            mode="year"
            :value="year"
            :allowClear="false"
            format="YYYY"
            :open="isopen"
            @openChange="onOpenChange"
            @panelChange="onPanelChange"
          ></a-date-picker>&nbsp;
          <router-link to="/dataBI/annualOperationIndex">
            查看报表
            <a-icon type="right-circle" theme="twoTone" />
          </router-link>
        </template>
        <a-row v-show="hasZhiBiao" :gutter="20">
          <a-col :span="8">
            <h1 class="headTitle">年度完成指标</h1>
            <div style="text-align: center;">
              <div id="bar3" style="height: 350px;"></div>

              <div style="display: inline-block; text-align: left;">
                <p v-for="(v, i) in data1" :key="i">
                  <a-badge :color="v.itemStyle.color" :text="v.nameEl" style="width: 110px"></a-badge>
                  <small
                    style="display: inline-block; color: grey; width: 100px; margin-right: 20px;"
                  >| {{v.rate}}%</small>
                  <span>
                    {{v.overData ? v.value1 : v.value}}
                    <small
                      v-if="v.overData"
                      style="color: #ff9900"
                    >+{{v.overData}}</small>
                  </span>
                </p>
              </div>
            </div>
          </a-col>

          <a-col :span="16">
            <h1 class="headTitle">季度完成指标</h1>
            <div id="bar4" style="height: 500px;"></div>
          </a-col>

          <a-col :span="24">
            <h1 class="headTitle">月度完成指标</h1>
            <div id="bar5" style="height: 500px;"></div>
          </a-col>
        </a-row>
        <a-empty v-show="!hasZhiBiao" :description="`${year.format('YYYY')}年度运营指标未配置`" />
      </a-card>
    </div>
  </div>
</template>

<script>
import moment from 'moment'
import DateSearcher from '@/components/DateSearch'
import 'echarts/lib/chart/bar'

import { queryTargetJiateByYear, queryJTBillRevenue, queryBIRevenueCurve, queryJTOrderRate } from '@/api/dataBI'

// bar1
const bar1Options = (legend, xData, yData) => ({
  tooltip: {
    trigger: 'axis'
  },
  legend: {
    data: legend
  },
  dataZoom: [
    {
      type: 'slider',
      realtime: true,
      start: 0,
      end: 100
    }
  ],
  grid: {
    left: '40',
    bottom: '40',
    right: '90',
    containLabel: true
  },
  xAxis: {
    type: 'category',
    data: xData
  },
  yAxis: [
    {
      type: 'value',
      name: '箱量（个）'
    },
    {
      type: 'value',
      name: '金额（元）'
    }
  ],
  series: [
    {
      name: '箱量',
      type: 'line',
      data: yData[1],
      itemStyle: {
        color: 'green'
      }
    },
    {
      name: '毛利',
      type: 'bar',
      data: yData[0],
      yAxisIndex: 1,
      barMaxWidth: 30,
      itemStyle: {
        color: '#3ba0ff'
      }
    },
    {
      name: '单日指标',
      type: 'line',
      yAxisIndex: 1,
      data: yData[2],
      itemStyle: {
        color: 'red'
      }
    }
  ]
})

// bar2
const radioGroup = [
  { key: 'containerNum', title: '箱量', suffix: '个' },
  { key: 'mileage', title: '里程', suffix: 'km' },
  { key: 'oilVolume', title: '耗油', suffix: 'L' },
  { key: 'profit', title: '毛利', suffix: '元' }
]
const pieOptions = (name, data, title) => ({
  tooltip: {
    trigger: 'item',
    formatter: '{a}<br/>{b}: {c}'
  },
  title: !title ? null : {
    ...title,
    x: 'center',
    y: '142px'
  },
  series: [
    {
      name: name,
      type: 'pie',
      radius: ['50%', '70%'],
      label: {
        show: false,
        position: 'center'
        // formatter: '{a|{b}}\n{b|{c}}',
        // rich: {
        //   a: {
        //     fontSize: 14,
        //     lineHeight: 30,
        //     height: 30,
        //     color: 'grey'
        //   },
        //   b: {
        //     fontSize: 24
        //   }
        // }
      },
      labelLine: {
        show: false
      },
      data
    }
  ]
})

const colors = ['#3ba0ff', '#36cbcb', '#4dcb73', '#fad337', '#f2637b', '#975fe4', '#f69c3b']
const OrderOptions = [
  { key: 'DOMESTIC_TRADE_EXPORTS', title: '内贸出口订单', color: colors[0] },
  { key: 'DOMESTIC_TRADE_IMPORTS', title: '内贸进口订单', color: colors[1] },
  { key: 'FOREIGN_TRADE_EXPORTS', title: '外贸出口订单', color: colors[2] },
  { key: 'FOREIGN_TRADE_IMPORTS', title: '外贸进口订单', color: colors[3] },
  { key: 'UNITED_TRANSPORT_EXPORTS', title: '联运出口订单', color: colors[4] },
  { key: 'UNITED_TRANSPORT_IMPORTS', title: '联运进口订单', color: colors[5] },
  { key: 'PURE_LAND_TRANSPORTS', title: '纯陆运订单', color: colors[6] }
]

export default {
  data () {
    return {
      colors,
      radioGroup,
      OrderOptions,
      isopen: false,
      bar1: null,
      form1: {
        startQueryDate: '', // 查询开始日期
        endQueryDate: '', // 查询结束日期
        type: '' // 类型；1按日、2按周、3按月、4按年
      },
      detail: {},
      // 运营指标
      hasZhiBiao: true,
      data1: [],
      data2: [],
      data3: [],
      year: moment(),
      loading: false,
      bar2: null,
      orderRateList: [],
      orderTypeCurrent: radioGroup[0].key,
      orderRates: []
    }
  },
  components: {
    [DateSearcher.name]: DateSearcher
  },
  methods: {
    initDateSearch (dateType, dateStr) { // 获得搜索日期, dateStr: [startDateStr, endDateStr]
      this.form1.type = dateType
      this.form1.startQueryDate = dateStr[0]
      this.form1.endQueryDate = dateStr[1]
      if (this.bar1) this.handleSearch1()
    },
    // 年份
    onOpenChange (status) {
      this.isopen = status
    },
    onPanelChange (v) {
      this.year = v
      this.isopen = false
      this.searchTarget()
    },
    // 营收曲线
    searchBar1 () {
      // 1
      queryJTBillRevenue(this.form1).then(rsp => {
        const g = rsp.data
        let rspData = {}
        for (let i in g) {
          rspData[i] = (g[i]).toFixed(2)
        }
        this.detail = rspData
      })
      // 2
      queryBIRevenueCurve(this.form1).then(rsp => {
        const legend = ['毛利', '箱量', '单日指标']
        let xData = []
        let yData1 = []
        let yData2 = []
        let yData3 = []

        rsp.data.forEach(v => {
          xData.push(v.date || v.month || v.year)
          yData1.push(v.profit.toFixed(2))
          yData2.push(v.number)
          yData3.push(v.quantity.toFixed(2))
        })

        this.bar1.setOption(bar1Options(legend, xData, [yData1, yData2, yData3]))
        window.setTimeout(() => { this.bar1.resize() })
      })
    },
    initOrderRate () {
      const data = this.orderRateList
      let bar2Data = []
      let result = data.length > 0 ? data : OrderOptions
      const type = radioGroup.filter(v => v.key === this.orderTypeCurrent)[0].title
      const suffix = radioGroup.filter(v => v.key === this.orderTypeCurrent)[0].suffix

      let resultData = 0
      result.map(v => {
        const t = OrderOptions.filter(w => w.key === (v.orderType || v.key))[0]
        const temp = this.orderTypeCurrent !== 'containerNum' ? (v[this.orderTypeCurrent] || 0).toFixed(2) : v[this.orderTypeCurrent] || 0
        bar2Data.push({
          ...v,
          name: t ? `${t.title}（${suffix}）` : '--',
          nameEl: t ? `${t.title}` : '--',
          value: temp,
          itemStyle: {
            color: t ? t.color : 'grey'
          }
        })
        resultData += v[this.orderTypeCurrent] || 0
      })
      this.bar2.setOption(pieOptions(type, bar2Data, {
        text: `${type}(${suffix})`,
        textStyle: {
          fontSize: 14,
          lineHeight: 30,
          height: 30,
          color: 'grey'
        },
        subtext: this.orderTypeCurrent !== 'containerNum' ? (Math.round(resultData * 100) / 100).toFixed(2) : (Math.round(resultData * 100) / 100).toFixed(0),
        subtextStyle: {
          fontSize: 24,
          color: 'black'
        }
      }))
      window.setTimeout(() => { this.bar2.resize() })

      this.orderRates = bar2Data.map(v => ({
        value: v.value,
        nameEl: v.nameEl,
        itemStyle: v.itemStyle,
        num: this.orderTypeCurrent !== 'containerNum' ? (v[this.orderTypeCurrent] || 0).toFixed(2) : v[this.orderTypeCurrent] || 0,
        rate: this.orderTypeCurrent !== 'containerNum' ? (v[this.orderTypeCurrent + 'Rate'] || 0).toFixed(2) : v[this.orderTypeCurrent + 'Rate'] || 0
      }))
    },
    searchOrderRate () {
      queryJTOrderRate(this.form1).then(rsp => {
        this.orderRateList = rsp.data
        this.initOrderRate()
      })
    },
    onChangeType () {
      this.initOrderRate()
    },
    handleSearch1 () {
      this.searchBar1()
      this.searchOrderRate()
    },
    dealTargetDatas (data) {
      // 1
      const overData = data.targetYearComplete - data.targetYear
      const overColor = '#ff9900'
      let arr = [
        {
          name: '已完成（元）',
          nameEl: '已完成',
          value: data.targetYearComplete.toFixed(2),
          rate: data.targetYearRate.toFixed(2),
          itemStyle: {
            color: colors[0]
          }
        },
        {
          name: '剩余指标（元）',
          nameEl: '剩余指标',
          value: data.targetYearRemain.toFixed(2),
          rate: (100 - data.targetYearRate < 0 ? 0 : 100 - data.targetYearRate).toFixed(2),
          itemStyle: {
            color: colors[1]
          }
        }
      ]
      if (overData > 0) {
        arr[0]['value1'] = data.targetYear
        arr[0].itemStyle.color = overColor
        arr[0]['overData'] = overData.toFixed(2)
      }
      this.data1 = arr
      // 2
      const seasonHead = ['一', '二', '三', '四']
      let seasonDataX = []
      let seasonData1 = []
      let seasonData2 = []
      seasonHead.forEach((v, i) => {
        seasonDataX.push(`第${v}季度`)
        seasonData1.push({
          name: `第${v}季度`,
          value: (data[`targetQuarter${i + 1}Complete`] || 0).toFixed(2),
          rate: (data[`targetQuarter${i + 1}Rate`] || 0).toFixed(2)
        })
        seasonData2.push({
          name: `第${v}季度`,
          value: (data[`targetQuarter${i + 1}`] || 0).toFixed(2)
        })
      })
      const option4 = {
        tooltip: {
          trigger: 'axis',
          formatter: p => {
            return `${p[0].name}<br/>完成指标(元)：${p[0].value}<br/>季度指标(元)：${p[1].value}<br/>完成比：${p[0].data.rate}%`
          }
        },
        legend: {
          data: ['完成指标', '季度指标'],
          right: '10%'
        },
        xAxis: {
          type: 'value'
        },
        yAxis: {
          type: 'category',
          data: seasonDataX,
          boundaryGap: false
        },
        series: [{
          name: '完成指标',
          data: seasonData1,
          type: 'bar',
          barMaxWidth: 30,
          itemStyle: {
            color: colors[0]
          }
        }, {
          name: '季度指标',
          data: seasonData2,
          type: 'line',
          smooth: true,
          itemStyle: {
            color: 'red'
          }
        }]
      }
      this.data2 = option4

      // 3
      const months = ['01', '02', '03', '04', '05', '06', '07', '08', '09', '10', '11', '12']
      let monthDataX = []
      let monthData1 = []
      let monthData2 = []
      months.forEach((v, i) => {
        monthDataX.push(`${v}月`)
        monthData1.push({
          name: `${v}月`,
          value: (data[`targetMonth${i + 1}Complete`] || 0).toFixed(2),
          rate: (data[`targetMonth${i + 1}Rate`] || 0).toFixed(2)
        })
        monthData2.push({
          name: `${v}月`,
          value: (data[`targetMonth${i + 1}`] || 0).toFixed(2)
        })
      })
      const option5 = {
        tooltip: {
          trigger: 'axis',
          formatter: p => {
            return `${p[0].name}<br/>完成指标(元)：${p[0].value}<br/>月度指标(元)：${p[1].value}<br/>完成比：${p[0].data.rate}%`
          }
        },
        legend: {
          data: ['完成指标', '月度指标'],
          right: '10%'
        },
        xAxis: {
          type: 'category',
          data: monthDataX,
          boundaryGap: false
        },
        yAxis: {
          type: 'value'
        },
        series: [{
          name: '完成指标',
          data: monthData1,
          type: 'bar',
          itemStyle: {
            color: colors[0]
          }
        }, {
          name: '月度指标',
          data: monthData2,
          type: 'line',
          smooth: true,
          itemStyle: {
            color: 'red'
          }
        }]
      }
      this.data3 = option5
    },
    searchTarget () {
      this.loading = true
      const year = this.year.format('YYYY')
      queryTargetJiateByYear({ year }).then(rsp => {
        if (rsp.data && rsp.data.id) {
          this.hasZhiBiao = true
          this.dealTargetDatas(rsp.data)
          this.bar3.setOption(pieOptions(`${year}年度指标`, this.data1, {
            text: `${year}年度指标（元）`,
            textStyle: {
              fontSize: 14,
              lineHeight: 30,
              height: 30,
              color: 'grey'
            },
            subtext: rsp.data.targetYear.toFixed(2),
            subtextStyle: {
              fontSize: 22,
              color: 'black'
            }
          }))
          this.bar4.setOption(this.data2)
          this.bar5.setOption(this.data3)
          window.setTimeout(() => { this.bar3.resize() })
          window.setTimeout(() => { this.bar4.resize() })
          window.setTimeout(() => { this.bar5.resize() })
          this.loading = false
        } else {
          this.hasZhiBiao = false
        }
      }).catch(() => { this.loading = false })
    }
  },
  mounted () {
    this.$nextTick(() => {
      // bar1
      this.bar1 = this.$echarts.init(document.getElementById('bar1'))
      // bar2
      this.bar2 = this.$echarts.init(document.getElementById('bar2'))
      this.handleSearch1()

      // target
      this.bar3 = this.$echarts.init(document.getElementById('bar3'))
      this.bar4 = this.$echarts.init(document.getElementById('bar4'))
      this.bar5 = this.$echarts.init(document.getElementById('bar5'))
      this.searchTarget()

      window.addEventListener('resize', () => {
        this.bar1.resize()
        this.bar2.resize()
        this.bar3.resize()
        this.bar4.resize()
        this.bar5.resize()
      })
    })
  }
}
</script>

<style lang="less" scoped>
.dot {
  position: relative;
  top: -1px;
  display: inline-block;
  width: 6px;
  height: 6px;
  vertical-align: middle;
  border-radius: 50%;
}
</style>
